import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wallpaper/api/manyACG.dart';
import 'package:wallpaper/components/images/image_list.dart';
import 'package:wallpaper/model/image_base.dart';
import 'package:wallpaper/pages/other/ManyACG/ManyACG_Search.dart';
import 'package:wallpaper/tools/route_animation.dart';

class ManyACG extends StatefulWidget {
  const ManyACG({super.key});

  @override
  State<ManyACG> createState() => _ManyACGState();
}

class _ManyACGState extends State<ManyACG> {
  final List<ImageBase> imgs = [];
  final Set ids = {};
  bool isLoading = false;
  int page = 1;
  late SharedPreferences prefs;
  int r18 = 0;
  int num = 35;

  Future<void> getR18() async {
    prefs = await SharedPreferences.getInstance();
    r18 = prefs.getInt('r18') ?? 0;
    getManyAcgRandomImages();
  }

  Future<void> getManyAcgRandomImages() async {
    if (!mounted || isLoading) return;
    setState(() {
      isLoading = true;
    });
    try {
      Response res = await getManyAcgRandom(
        page: page,
        page_size: num,
        r18: r18,
        limit: num,
      );
      List data = res.data['data'];
      for (var item in data) {
        // 已经存在则跳过
        if (ids.contains(item['pictures'][0]['id'])) continue;
        ids.add(item['pictures'][0]['height']);
        // avif 解码效率过低 容易造成卡顿 等问题，所以这里只使用 webp 格式
        String largePathResult = item['pictures'][0]['regular'];
        if (largePathResult.contains('.avif')) continue;
        String smallPathResult = item['pictures'][0]['thumbnail'];
        smallPathResult = smallPathResult.contains('.avif')
            ? largePathResult
            : smallPathResult;
        imgs.add(ImageBase(
          largePath: largePathResult,
          smallPath: smallPathResult,
          width: item['pictures'][0]['width'],
          height: item['pictures'][0]['height'],
          tags: item['tags'].join(' '),
        ));
      }
    } catch (e) {
      debugPrint(e.toString());
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getR18();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;
    return Scaffold(
      // 右下角悬浮按钮
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          RouteAnimation().animateRoute(
            context,
            ManyacgSearch(r18: r18),
          );
        },
        child: Icon(
          Icons.search,
          color: theme.onSurface,
        ),
      ),
      body: ImageList(
        imageList: imgs,
        isLoading: isLoading,
        isWaterfallFlow: true,
        onImageBottomLoading: () {
          page += 1;
          getManyAcgRandomImages();
        },
        emptyHeight: 20,
        onImageListRefresh: () {
          setState(() {
            imgs.clear();
            page = 1;
            ids.clear();
          });
          getManyAcgRandomImages();
        },
      ),
    );
  }
}
